<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use RtcTokenBuilder2;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;

class Live extends BaseController {
    public function index() {
        // $appId = "64dce295a4274bc2bf4ab6b028b0ec83";
        // $appCerficicate = "fe65e76014234092a2b9b37396f3cf26";
        // $uid = "1";
        // $tokenExpirationInSeconds = 3600;
        // $privilegeExpirationInSeconds = 3600;
        // $token = RtcTokenBuilder2::buildTokenWithUid($appId, $appCerficicate, $uid, RtcTokenBuilder2::ROLE_PUBLISHER, $tokenExpirationInSeconds, $privilegeExpirationInSeconds);
        // return $token;
    }

public function requestVideoCall() {
    try {
        // 权限认证
        $token = Request::header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
        $token = $matches[1];
        $caller = Db::name('think_users')->where('token', $token)->find();
        if (!$caller) {
            return json(['code' => 401, 'msg' => 'token无效']);
        }

        $callerId = $caller['id']; // 主叫用户 ID
        $receiverUserID = Request::param('id'); // 被叫用户 ID
        // 检查被叫用户是否存在
        $receiver = Db::name('think_users')->where('id', $receiverUserID)->find();
        if (!$receiver) {
            return json(['code' => 404, 'msg' => '被叫用户不存在']);
        }
        if (!$caller["is_vip"]) {
            # code...
            return json(['code' => 403, 'msg' => 'please upgrade to VIP to use video call feature']);
        }
        
        // Agora 配置
        $channelName = "video_chat_" . uniqid(); // 生成唯一频道 ID
        
        $factory = (new Factory)
            ->withServiceAccount(__DIR__ . '/../../thirdparty/fcm/fcm.json');
        $messaging = $factory->createMessaging();
        $message = CloudMessage::fromArray([
            "token"=>$receiver["apns_token"],
            'notification' => [
                'title' => '有人向你发起视频通话',
                'body' => '点击接受通话',
            ],
            'apns' => [
                'payload' => [
                    'aps' => [
                        "mutable-content"=>1, // 设置 content-available
                        "content-available"=>1
                    ],
                    'type' => 'video_call',
                    'channel_id' => $channelName,
                    "avatar"=>$caller["avatar"],
                ],
            ],
            'data' => [
                'type' => 'video_call',
                'channel_id' => $channelName
            ],
        ]);
        $messaging->send($message);
        // 保存视频聊天记录到数据库
        Db::name('video_chat_records')->insert([
            'caller_id' => $callerId,
            'receiver_id' => $receiver['id'],
            'channel_id' => $channelName,
            'start_time' => date('Y-m-d H:i:s'),
            'status' => 'calling',
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        // 返回 Token 和频道 ID
        return json([
            'code' => 200,
            'msg' => '视频通话请求成功',
            'data' => [
                'channel_id' => $channelName
            ],
        ]);
    } catch (\Exception $e) {
        return json([
            'code' => 500,
            'msg' => '视频通话请求失败',
            'error' => $e->getMessage(),
        ]);
    }
}
    public function responseVideoCall() {
        $token = Request::header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
        $token = $matches[1];
        $user = Db::name('think_users')->where('token', $token)->find();
        if (!$user) {
            return json(['code' => 401, 'msg' => 'token无效']);
        }
        $channelId = Request::param('channel_id');
        $receive = Request::param('receive');
        $callRecord = Db::name('video_chat_records')
            ->where('channel_id', $channelId)
            ->find();
        if (!$callRecord) {
            return json(['code' => 404, 'msg' => '未找到通话记录']);
        }
        $caller_id = $callRecord['caller_id'];
        $receiver_id = $callRecord['receiver_id'];
        $request_user_id = $user['id'];
        $userToken = '';
        if ($request_user_id == $caller_id) {
            # code...
            //主叫挂断，发消息给被叫
            $receiver = Db::name('think_users')->where('id', $receiver_id)->find();
            $userToken = $receiver['apns_token'];
        } else if ($request_user_id == $receiver_id) {
            //发消息给主叫
            $caller = Db::name('think_users')->where('id', $caller_id)->find();
            $userToken = $caller['apns_token'];
        } else {
            return json(['code'=> 404, 'msg'=> 'permission denied']);
        }
        if (!$receive) {
            # code...
            //如果是挂断
            //看看是主叫挂断还是被叫挂断
            $factory = (new Factory)
                ->withServiceAccount(__DIR__ . '/../../thirdparty/fcm/fcm.json');
            $messaging = $factory->createMessaging();
            $message = CloudMessage::fromArray([
                "token"=>$userToken,
                'data' => [
                    'type' => 'call_response',
                    'receive' => false,
                    "channel_id"=>$channelId,
                ],
            ]);
            $messaging->send($message);
            $status = $callRecord['status'];
            if ($request_user_id == $caller_id) {
            # code...
            //主叫挂断，看聊天状态，要是进行中，状态应该是ended
            //要还没接，那么是missed
                if ($status == 'active') {
                # code...
                    Db::name('video_chat_records')
                        ->where('channel_id', $channelId)
                        ->update([
                            "status"=>"ended"
                        ]);
                } else if ($status == 'calling') {
                    Db::name('video_chat_records')
                        ->where('channel_id', $channelId)
                        ->update([
                            "status"=>"missed"
                        ]);
                }
            } else if ($request_user_id == $receiver_id) {
                if ($status == 'active') {
                    Db::name('video_chat_records')
                        ->where('channel_id', $channelId)
                        ->update([
                            "status"=>"ended"
                        ]);
                } else if ($status == 'calling') {
                    Db::name('video_chat_records')
                        ->where('channel_id', $channelId)
                        ->update([
                            "status"=>"declined"
                        ]);
                }
            }
            return json([
                'code' => 200,
                'msg' => '挂断成功'
            ]);
        }

        $appId = env("AGORA_APP_ID");
        $appCertificate = env("AGORA_APP_CERTIFICATE");
        $tokenExpirationInSeconds = 3600; // Token 有效期（秒）
        $privilegeExpirationInSeconds = 3600; // 权限有效期（秒）
        $callerToken = RtcTokenBuilder2::buildTokenWithUid(
            $appId,
            $appCertificate,
            $channelId,
            0,
            RtcTokenBuilder2::ROLE_PUBLISHER,
            $tokenExpirationInSeconds,
            $privilegeExpirationInSeconds
        );
        $receiverToken = RtcTokenBuilder2::buildTokenWithUid(
            $appId,
            $appCertificate,
            $channelId,
            0,
            RtcTokenBuilder2::ROLE_PUBLISHER,
            $tokenExpirationInSeconds,
            $privilegeExpirationInSeconds
        );
        //入库
        Db::name("video_chat_records")->where("channel_id", $channelId)->update([
            "caller_token"=>$callerToken,
            "receiver_token"=>$receiverToken,
            "status"=>"active"
        ]);
        $factory = (new Factory)
            ->withServiceAccount(__DIR__ . '/../../thirdparty/fcm/fcm.json');
        $messaging = $factory->createMessaging();
        $message = CloudMessage::fromArray([
            "token"=>$userToken,
            'data' => [
                'type' => 'call_response',
                'receive' => true,
                "channel_id"=>$channelId,
                "channel_token"=>$callerToken,
                "status"=>"active"
            ],
        ]);
        $messaging->send($message);
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                "channelId" => $channelId,
                "token" => $receiverToken
            ]
        ]);
    }

    public function updateChannelUid() {
        $token = Request::header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
        $token = $matches[1];
        $user = Db::name('think_users')->where('token', $token)->find();
        if (!$user) {
            return json(['code' => 401, 'msg' => 'token无效']);
        }
        $channelId = Request::param('channel_id');
        $callRecord = Db::name('video_chat_records')
            ->where('channel_id', $channelId)
            ->find();
        $aid = Request::param('aid');
        if (!$callRecord) {
            return json(['code' => 404, 'msg' => '未找到通话记录']);
        }
        if ($user["id"] == $callRecord["caller_id"]) {
            Db::name('video_chat_records')
            ->where('channel_id', $channelId)
            ->update([
                'caller_aid'=>$aid
            ]);
            return json(['code' => 200, 'msg' => 'success']);
        } else if ($user["id"] == $callRecord["receiver_id"]) {
            Db::name('video_chat_records')
            ->where('channel_id', $channelId)
            ->update([
                'receiver_aid'=>$aid
            ]);
            return json(['code' => 200, 'msg' => 'success']);
        } else {
            //非法
            return json(['code' => 404, 'msg' => '无权限']);
        }
    }

    //获取频道中双方的昵称，头像
    public function getUsersProfile() {
        try {
        // 权限认证
        $token = Request::header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
        $token = $matches[1];
        $user = Db::name('think_users')->where('token', $token)->find();
        if (!$user) {
            return json(['code' => 401, 'msg' => 'token无效']);
        }
        $channel_id = Request::param('channel_id');
        $callRecord = Db::name('video_chat_records')
            ->where('channel_id', $channel_id)
            ->find();
        if (!$callRecord) {
            return json(['code' => 404, 'msg' => '未找到通话记录']);
        }
        $localAvatar = $user["avatar"];
        $localName = $user["nickname"];
        $remoteId = null;
        if ($user["id"] == $callRecord["caller_id"]) {
            # code...
            $remoteId = $callRecord["receiver_id"];
        } else if ($user["id"] == $callRecord["receiver_id"]) {
            $remoteId = $callRecord["caller_id"];
        } else {
            json(['code' => 401, 'msg' => 'no permission']);
        }
        $remoteUser = Db::name('think_users')->where('id', $remoteId)->find();
        $remoteAvatar = $remoteUser["avatar"];
        $remoteName = $remoteUser["nickname"];
        return json([
            'code' => 200,
            'msg' => '',
            'data' => [
                'local' => ["avatar"=>$localAvatar, "name"=>$localName],
                'remote' => ["avatar"=>$remoteAvatar, "name"=>$remoteName]
            ],
        ]);
    } catch (\Exception $e) {
        return json([
            'code' => 500,
            'msg' => 'error occured',
            'error' => $e->getMessage(),
        ]);
    }
    }
}